<?php
declare (strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class DbDict extends Command
{
    protected function configure()
    {
        $this->setName('生成数据库数据字典')
            ->setDescription('ok');
    }

    protected function execute(Input $input, Output $output)
    {
        $file = app()->getRootPath() . 'public/db_dict.html'; //存储目录文件地址
        $db_name = config('database.connections.mysql.database'); //需要生成的库名称

        $list = Db::query('show tables');
        $str = '';
        foreach ($list as $value) {

            $field = 'Tables_in_' . $db_name;

            $sql = "SELECT a.table_name,a.table_comment,b.COLUMN_NAME,b.column_comment,b.column_type,b.column_key,b.COLUMN_DEFAULT FROM";
            $sql .= " information_schema. TABLES a LEFT JOIN information_schema. COLUMNS b ON a.table_name = b.TABLE_NAME WHERE";
            $sql .= " a.table_schema = '{$db_name}' AND a.table_name ='{$value[$field]}' ORDER BY a.table_name";

            $data = Db::query($sql);

            $check = [];

            foreach ($data as $k => $v) {
                if(isset($check[$v['COLUMN_NAME']])) {
                    continue;
                }
                $check[$v['COLUMN_NAME']] = 1;

                if ($k == 0) {
                    $str .= <<<AA
<p>{$v['table_name']}{$v['table_comment']}</p>
<table border="1">
    <tbody>
        <tr style="height:15.6000pt; ">
            <th><span>字段名</span></th>
            <th><span>数据类型</span></th>
            <th><span>默认值</span></th>
            <th><span>备注</span></th>
        </tr>
        <tr>
            <td class="c1 td1">{$v['COLUMN_NAME']}</td>
            <td class="c2 td1">{$v['column_type']}</td>
            <td class="c3 td1">{$v['COLUMN_DEFAULT']}column_comment</td>
            <td class="c4 td1">{$v['column_comment']}</td>
        </tr>
AA;
                } else {
                    $str .= "
                    <tr>
                        <td class=\"c1 td2\">{$v['COLUMN_NAME']}</td>
                        <td class=\"c2 td2\">{$v['column_type']}</td>
                        <td class=\"c3 td2\">{$v['COLUMN_DEFAULT']}</td>
                        <td class=\"c6 td2\">{$v['column_comment']}</td>
                    </tr>";
                }
            }
            $str .= '</tbody></table>';
        }

        try{
            file_put_contents($file,$this->createHtml($str));
        }catch (\Exception $e) {
            $output->writeln('处理失败:' . $e->getMessage());
        }

        $output->writeln('处理时间:' . date('Y-m-d H:i:s'));
    }


    private function createHtml($str)
    {
        $html = '<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>数据库字典</title>
</head>
<body>
'.$str.'
</body>
</html>';
        return $html;
    }

}